<?php
/**
* 附近主题指令支持
*/
class weixin_cmd_upload_picture extends mc_weixin_cmd
{
	protected $keyword    = 'upload';
	protected $name       = '上传商户图片';
	protected $intro      = "将图片上传至商户的相册内。";

	protected $menu_types 	= array('pic_sysphoto','pic_photo_or_album','pic_weixin');
	protected $roles			= array('subject');

	//获取主题数量
	private $search_num = 8;
	private $usermsg;

	public function match($message_obj, $role_obj, $session_obj)
	{
		$mark = strtolower($this->keyword);
		if($message_obj->MsgType == 'event' && in_array($message_obj->Event,$this->menu_types)) {
			return strtolower($message_obj->EventKey) == $mark;
		} elseif($message_obj->MsgType == 'image') {
			//sleep(1); //延迟1秒，等待菜单事件
			return true;
		}
	}

	public function execute($message_obj, $role_obj, $session_obj)
	{
		$session_obj->action = mc_weixin_session::ACTION_RESET;
		if($message_obj->MsgType == 'event' && in_array($message_obj->Event,$this->menu_types)) {
			$session_obj->data->custom_menu = 1;
			$session_obj->data->count = (int)$message_obj->SendPicsInfo->count;
			// $session_obj->data->PicList = array();
			// foreach ($message_obj->SendPicsInfo->PicList->item as $item) {
			// 	$session_obj->data->PicList[] = _T($item->PicMd5Sum);
			// }
			$session_obj->action = mc_weixin_session::ACTION_SAVE;
		} else {

			$mp_openid 		= $message_obj->ToUserName;
			$user_openid 	= $message_obj->FromUserName;
			$user_unionid 	= '';
			$bind_obj = new mc_weixin_bind($mp_openid, $user_openid, $user_unionid);
			if($bind_obj->has_error()) {
				if($bind_obj->erron() == -2) $bind_obj->unbind(); //被绑定账号已不存在，删除绑定记录
				$content = '您的微信帐号尚未绑定网站会员帐号，<a href="'.$bind_obj->bind_link().'">请点击这里绑定微信帐号</a>';
			} else {
				if(!$bind_obj->login()) {
					$content = '网站帐号登录失败，无法上传图片。';
				} else {
					if($message_obj->MsgType == 'image' && $session_obj->data->custom_menu) {
						$session_obj->data->count--;
						$pics[] = array(
							'PicUrl'	=> trim($message_obj->PicUrl),
							'MediaId'	=> _T($message_obj->MediaId),
						);
						$content = $this->save_picture($role_obj->role_id, $pics);
						$session_obj->action = mc_weixin_session::ACTION_SAVE;

						//$content .= "({$session_obj->data->count})";
						// if($session_obj->data->count <= 0) {
						// 	$content .= "\n图片上传完毕。";
						// 	$session_obj->action = mc_weixin_session::ACTION_RESET;
						// }

					} else if($message_obj->MsgType == 'image') {
						if(!$session_obj->data->pics) {
							$session_obj->data->pics = array();
						}
						$session_obj->data->pics[] = array(
							'PicUrl'	=> trim($message_obj->PicUrl),
							'MediaId'	=> _T($message_obj->MediaId),
						);
						$content = "您上传了".count($session_obj->data->pics)."张图片，是否添加到商铺相册？\n请回复 Y 上传，或者 N 取消。";
						$session_obj->action = mc_weixin_session::ACTION_SAVE;
					} else if($message_obj->MsgType == 'text') {
						if(in_array(strtoupper($message_obj->Content), array('Y','YES','是'))) {
							$content = $this->save_picture($role_obj->role_id, $session_obj->data->pics);
						} elseif(strtoupper($message_obj->Content)=='N') {
							$content = '取消上传。';
						}
					} else {
						$content = "您上传了图片，是否添加到商铺相册？\n请回复 Y 上传，或者 N 取消。";
						$session_obj->action = mc_weixin_session::ACTION_SAVE;
					}
				}
			}
			if($content) {
				$reply_obj = mc_weixin_reply::factory('text');
				$reply_obj->set_content($content);
				$reply_obj->set_user($message_obj->FromUserName, $message_obj->ToUserName)->send($role_obj);				
			}
		}

		return true;
	}

	protected function save_picture($sid, $pics)
	{
		if(!$pics) return '找不到图片。';
		$total = count($pics);
		$content = '';
		foreach ($pics as $i => $pic) {
			$result = $this->download_picture($pic['PicUrl'], $pic['MediaId']);
			if(!$result) {
				$msg = $this->error(); 
				$this->error_clear();
			} else {
				$P = _G('loader')->model('item:picture');
				$post = array(
					'sid' => $sid,
					'local_picture' => $result,
				);
				$picid = $P->save($post, true);
				if($P->has_error()) {
					$msg = $P->error();
				} else {
					$msg = '上传成功！';
					if(RETURN_EVENT_ID == 'global_op_succeed_check') {
						$msg .= '(需要审核才能显示)。';
					} else {
						$msg .= '';
					}
				}
			}
			$content .= ($total>1?("[".($i+1)."/$total]"):"").$msg."\n";
		}
		$content .= "\n<a href=\"".U("item/mobile/do/album/sid/$sid", true)."\">点击这里查看商铺相册</a>";
		return $content;
	}

	private function download_picture($PicUrl, $MediaId)
	{
		static $cts = array('image/x-png'=>'.png','image/png'=>'.png','image/jpeg'=>'.jpg','image/gif'=>'.gif');

		$array = get_headers($PicUrl, 1);
		if(!$array && !in_array(strtolower($array['Content-Type']), array_keys ($cts))) {
			return $this->add_error('不是图片数据。',-1);
		}
		if(!function_exists('curl_exec')) {
			return $this->add_error('网站服务器未开启curl模块。',-2);
		}
		$curl = curl_init($PicUrl);
		$filename = mt_rand(1000,9999).'_'._G('timestamp').$cts[strtolower($array['Content-Type'])];
		$filepath = 'uploads/temp/'.$filename;
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$imageData = curl_exec($curl);
		if(!curl_errno($curl)) {
			if(!file_put_contents(MUDDER_ROOT.$filepath, $imageData)) {
				return $this->add_error('无法保存到网站服务器。',-3);
			}
		} else {
			return $this->add_error('图片下载失败：'.curl_error($curl));
		}
		return $filepath;
	}
}
/** end **/